﻿using InventoryManagementSystem.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Infrastructure.UI;

namespace InventoryManagementSystem
{
    public sealed partial class ReportPage : InventoryManagementSystem.Common.LayoutAwarePage
    {
        ObservableCollection<ChartData> charts = new ObservableCollection<ChartData>();

        public ReportPage()
        {
            this.InitializeComponent();

            this.EnablePrivacyPolicy(PrivacyPolicy.RunXiaDianQi);
        }

        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ShowInProgress("正在生成报表");

            var date = DateTime.Now;
            date = new DateTime(date.Year, date.Month, 1);

            for (int i = 0; i > -3; i--)
            {
                var dateInMonth = date.AddMonths(i);

                ChartData chart = new ChartData();
                chart.Title = dateInMonth.Month + "月销售统计";
                do
                {
                    var orders = await DataStore.GetSellOrdersByDate(dateInMonth);
                    var totalSell = orders.Sum(order => order.TotalPrice);
                    totalSell = Math.Abs(totalSell);
                    chart.Data.Add(new NameValue(dateInMonth.Day.ToString(), (uint)totalSell));
                    dateInMonth = dateInMonth.AddDays(1);
                } while (dateInMonth.Month == date.AddMonths(i).Month);

                charts.Add(chart);
            }

            DefaultViewModel["Charts"] = charts;

            HideInProgress();
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void ShowInProgress(string text)
        {
            inProgressTextBlock.Text = text;
            contentGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            inProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void HideInProgress()
        {
            contentGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
            inProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }
    }
}
